package com.rc.saas.tenant.controller.enterprise;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.constant.ShiroConstants;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.TimeUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.model.discount.TenantDiscountPolicy;
import com.rc.saas.tenant.model.discount.TenantDiscountPolicyExample;
import com.rc.saas.tenant.model.discount.TenantDiscountStation;
import com.rc.saas.tenant.model.discount.TenantDiscountStationExample;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.enterprise.EnterpriseMemberApply;
import com.rc.saas.tenant.model.enterprise.EnterpriseSubmember;
import com.rc.saas.tenant.model.enterprise.EnterpriseSubmemberShare;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.tenant.TenantUserExample;
import com.rc.saas.tenant.search.enterprise.EnterpriseMemberSearch;
import com.rc.saas.tenant.search.enterprise.EnterpriseOrderSearch;
import com.rc.saas.tenant.search.enterprise.EnterpriseSubMemberSearch;
import com.rc.saas.tenant.search.member.MemberAccountRecordSearch;
import com.rc.saas.tenant.search.order.OrderSearch;
import com.rc.saas.tenant.service.discount.TenantDiscountPolicyService;
import com.rc.saas.tenant.service.discount.TenantDiscountStationService;
import com.rc.saas.tenant.service.discount.TenantDiscountTimeService;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberApplyService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.enterprise.EnterpriseSubmemberService;
import com.rc.saas.tenant.service.enterprise.EnterpriseSubmemberShareService;
import com.rc.saas.tenant.service.member.MemberAccountRecordService;
import com.rc.saas.tenant.service.member.MemberAccountService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.discount.DiscountStationSaveVo;
import com.rc.saas.tenant.vo.discount.DiscountTimeSaveVo;
import com.rc.saas.tenant.vo.discount.EnterprieseStationVo;
import com.rc.saas.tenant.vo.discount.EnterpriseDiscountResultVo;
import com.rc.saas.tenant.vo.enterprise.*;
import com.rc.saas.tenant.vo.member.*;
import com.rc.saas.tenant.vo.order.OrderPrintVo;
import com.rc.saas.tenant.vo.order.OrderResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author frog
 * @data 2019/9/26
 */
@Controller
@RequestMapping("/enterpriseMember")
public class EnterpriseMemberController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(EnterpriseMemberController.class);

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private UploadComponent uploadComponent;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private EnterpriseSubmemberService enterpriseSubmemberService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private EnterpriseSubmemberShareService enterpriseSubmemberShareService;

    @Autowired
    private TenantDiscountPolicyService tenantDiscountPolicyService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private TenantDiscountStationService tenantDiscountStationService;


    @Autowired
    private TenantDiscountTimeService tenantDiscountTimeService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberAccountRecordService memberAccountRecordService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private EnterpriseMemberApplyService enterpriseMemberApplyService;

    /**
     * 跳转企业会员页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String enterpriseMemberPage() {
        return "/templates/enterprise/enterpriseMember/enterPriseMember";
    }

    /**
     * 返回企业会员列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listEnterpriseMember", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listEnterpriseMember(EnterpriseMemberSearch search) {
        PageInfo<EnterpriseMemberResult> pageInfo = enterpriseMemberService.listPageEnterpriseMember(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转增加企业子会员页面
     *
     * @return
     */
    @RequestMapping(value = "/addEnterpriseSubmember/{enterpriseId}", method = RequestMethod.GET)
    public String addEnterpriseSubmember(@PathVariable("enterpriseId") Long enterpriseId, Model model) {
        model.addAttribute("enterpriseId", enterpriseId);
        return "/templates/enterprise/enterpriseMember/addEnterpriseSubmember";
    }

    /**
     * 保存企业子会员
     *
     * @return
     */
    @RequestMapping(value = "/saveEnterpriseSubmember", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveEnterpriseSubmember(HttpSession session, String addType, String mobile,
                                             String verificationCode, String batchMobile, Long enterpriseId) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();
            //addType 0:新增一个   1:批量新增
            if ("0".equals(addType)) {
                if (!BeanUtil.isValid(mobile, verificationCode)) {
                    return TResponse.FAIL("请输入正确的参数");
                }

                String sessionAttr = ShiroConstants.SESSION_ADDMEMBER_ENTERPRISEMEMBER_KEY + mobile;
                String sessionAuthCode = (String) session.getAttribute(sessionAttr);
                if (StringUtils.isBlank(sessionAuthCode)) {
                    return TResponse.FAIL("未申请验证码");
                }

                if (!verificationCode.equals(sessionAuthCode.substring(0, 6))) {
                    return TResponse.FAIL("验证码错误");
                }

                TResponse tResponse = enterpriseMemberService.insertOneEnterpriseSubmember(mobile, enterpriseId, user);
                return tResponse;
            } else if ("1".equals(addType)) {
                if (!BeanUtil.isValid(batchMobile)) {
                    return TResponse.FAIL("请输入正确的参数");
                }
                TResponse tResponse = enterpriseMemberService.insertBatchEnterpriseSubmember(batchMobile, enterpriseId, user);
                return tResponse;
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存企业子会员失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 获取手机短信验证码
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/getReviewAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public TResponse getReviewAuthCode(HttpSession session, String mobile) {
        if (!BeanUtil.isValid(mobile)) {
            return TResponse.FAIL("请输入手机号");
        }

        TenantUser user = ShiroUtils.getSessionUser();
        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
        //验证码
        String smscode = uidGenerator.genSmsAuthCode();

        SendSmsResponse sendResult = AliyunSmsUtil.sendSms(mobile, smscode, AliyunSmsTemplateEnum.ADD_SUBMEMBER, tenant.getSmsSign());

        if (sendResult == null) {
            logger.error("短信系统异常");
            return TResponse.FAIL("短信系统异常");
        }

        if ("OK".equals(sendResult.getCode())) {
            // 更新sms表
            tenantSmsService.updateTenantSmsByTenantCode(tenant.getTenantCode(), mobile, "0", "tenant,getTicketAuthCode:获取验证码 ,进行添加企业子会员功能:" + mobile, "获取验证码 ,进行添加企业子会员功能");
        } else {
            logger.error("短信系统异常:" + sendResult.getMessage());
        }

        //将登录验证码保存到会话中
        String sessionAttr = ShiroConstants.SESSION_ADDMEMBER_ENTERPRISEMEMBER_KEY + mobile;
        String sessionAuthCode = smscode + System.currentTimeMillis();
        session.setAttribute(sessionAttr, sessionAuthCode);

        logger.error("获取手机短信验证码 mobile:{},sessionAttr:{},sessionAuthCode:{}", mobile, sessionAttr, sessionAuthCode);

        return TResponse.SUCCESS("验证码已发送");
    }


    /**
     * 跳转企业子会员页面
     *
     * @return
     */
    @RequestMapping(value = "/enterpriseSubmember/{enterpriseId}", method = RequestMethod.GET)
    public String enterpriseSubmember(@PathVariable("enterpriseId") Long enterpriseId, Model model) {
        model.addAttribute("enterpriseId", enterpriseId);
//        return "/templates/enterprise/enterpriseMember/enterpriseSubmember";
        return "templates/enterprise/enterpriseSubmemberApply/enterpriseSubmemberApply";
    }


    /**
     * 返回企业子会员列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listEnterpriseSubmember", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listEnterpriseSubmember(EnterpriseSubMemberSearch enterpriseSubMemberSearch) {
        PageInfo<EnterPriseSubMemberResult> pageInfo = enterpriseSubmemberService.searchByCondition(enterpriseSubMemberSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出企业子会员列表
     *
     * @param enterpriseSubMemberSearch
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/exportEnterpriseSubmember", method = RequestMethod.GET)
    public TResponse exportEnterpriseSubmember(EnterpriseSubMemberSearch enterpriseSubMemberSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        if (enterpriseSubMemberSearch.getCount() == 0 || enterpriseSubMemberSearch.getCount() == null) {
            enterpriseSubMemberSearch.setCount(enterpriseSubMemberSearch.getLimit());
        }
        if (enterpriseSubMemberSearch.getCount() > 150000) {
            return TResponse.FAIL("最多导出15万数据");
        }

        //导出拼接开始条数
        enterpriseSubMemberSearch.setOffset(enterpriseSubMemberSearch.getLimit() * (enterpriseSubMemberSearch.getOffset() - 1));

        try {
            ExportUtils.setDefaultPaging(enterpriseSubMemberSearch);
            List<EnterpriseSubmemberExportVo> list = enterpriseSubmemberService.listEnterpriseSubmember(enterpriseSubMemberSearch);

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("企业子会员列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), EnterpriseSubmemberExportVo.class).sheet("企业子会员列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出企业子会员列表失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 跳转企业子会员订单页面
     *
     * @return
     */
    @RequestMapping(value = "/submemberOrder/{memberId}", method = RequestMethod.GET)
    public String submemberOrder(@PathVariable("memberId") Long memberId, Model model) {
        model.addAttribute("memberId", memberId);
        return "/templates/enterprise/enterpriseMember/submemberOrder";
    }


    /**
     * 返回企业子会员订单列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listSubmemberOrder", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listSubmemberOrder(OrderSearch orderSearch) {
        PageInfo<OrderResult> pageInfo = orderInfoService.listPageByCondition(orderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 冻结/恢复企业子会员
     *
     * @return
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateStatus(Long memberId) {
        try {
            TResponse tResponse = enterpriseSubmemberService.updateStatus(memberId);
            return tResponse;
        } catch (Exception e) {
            logger.error("变更企业子会员状态失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 注销企业子会员
     *
     * @return
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @ResponseBody
    public TResponse cancel(Long memberId) {
        try {
            TResponse tResponse = enterpriseSubmemberService.updateLogout(memberId);
            return tResponse;
        } catch (Exception e) {
            logger.error("企业子会员注销失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 还原企业子会员
     *
     * @return
     */
    @RequestMapping(value = "/reductionSubMember", method = RequestMethod.POST)
    @ResponseBody
    public TResponse reductionSubMember(Long submemberOutId) {
        try {
            TResponse tResponse = enterpriseSubmemberService.updateReductionSubMember(submemberOutId);
            return tResponse;
        } catch (Exception e) {
            logger.error("企业子会员注销失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转企业会员订单页面
     *
     * @return
     */
    @RequestMapping(value = "/enterpriseOrder/{enterpriseId}", method = RequestMethod.GET)
    public String enterpriseOrder(@PathVariable("enterpriseId") Long enterpriseId, Model model) {
        model.addAttribute("enterpriseId", enterpriseId);
        return "/templates/enterprise/enterpriseMember/enterpriseOrder";
    }


    /**
     * 返回企业会员订单列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listEnterpriseOrder", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listEnterpriseOrder(EnterpriseOrderSearch enterpriseOrderSearch) {
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseOrderSearch.getEnterpriseId());
        enterpriseOrderSearch.setMemberId(enterpriseMember.getMemberId());
        PageInfo<OrderResult> pageInfo = orderInfoService.listPageEnterpriseOrder(enterpriseOrderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 导出订单列表
     */
    @ResponseBody
    @RequestMapping("/exportEnterpriseOrder")
    public void exportEnterpriseOrder(EnterpriseOrderSearch enterpriseOrderSearch, HttpServletResponse response) throws Exception {
        ExportUtils.setDefaultPaging(enterpriseOrderSearch);
        if (enterpriseOrderSearch.getCount() == 0 || enterpriseOrderSearch.getCount() == null) {
            enterpriseOrderSearch.setCount(enterpriseOrderSearch.getLimit());
        }
        if (enterpriseOrderSearch.getCount() > 20000) {
            enterpriseOrderSearch.setCount(20000);
        }

        try {

            //导出拼接开始条数
            enterpriseOrderSearch.setOffset(enterpriseOrderSearch.getLimit() * (enterpriseOrderSearch.getOffset() - 1));
            EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseOrderSearch.getEnterpriseId());
            enterpriseOrderSearch.setMemberId(enterpriseMember.getMemberId());
            List<OrderPrintVo> list = orderInfoService.exportEnterpriseOrder(enterpriseOrderSearch);

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderPrintVo.class).sheet("订单列表").doWrite(list);
        } catch (Exception e) {
            logger.error("导出订单失败", e.getMessage());
        }
    }


    /**
     * 跳转企业会员注销页面
     *
     * @return
     */
    @RequestMapping(value = "/cancel/{enterpriseId}", method = RequestMethod.GET)
    public String logout(@PathVariable("enterpriseId") Long enterpriseId, Model model) {
        model.addAttribute("enterpriseId", enterpriseId);
        return "/templates/enterprise/enterpriseMember/cancelSubMember";
    }


    /**
     * 返回企业会员注销列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listLogout", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listLogout(EnterpriseSubMemberSearch enterpriseSubMemberSearch) {
        PageInfo<EnterpriseSubmemberOutResult> pageInfo = enterpriseSubmemberService.listLogout(enterpriseSubMemberSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转企业会员增加共享余额页面
     *
     * @return
     */
    @RequestMapping(value = "/addEnterpriseShare/{enterpriseId}", method = RequestMethod.GET)
    public String addEnterpriseShare(@PathVariable("enterpriseId") Long enterpriseId, Model model) {
        model.addAttribute("enterpriseId", enterpriseId);
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseId);
        EnterpriseSubmemberShare submemberShare = enterpriseSubmemberShareService.selectByMemberId(enterpriseMember.getMemberId());
        model.addAttribute("submemberShare", submemberShare);
        return "/templates/enterprise/enterpriseMember/addEnterpriseShare";
    }

    /**
     * 跳转子会员会员增加共享余额页面
     *
     * @return
     */
    @RequestMapping(value = "/addSubmemberShare/{memberId}", method = RequestMethod.GET)
    public String addSubmemberShare(@PathVariable("memberId") Long memberId, Model model) {
        model.addAttribute("memberId", memberId);
        EnterpriseSubmemberShare submemberShare = enterpriseSubmemberShareService.selectByMemberId(memberId);
        model.addAttribute("submemberShare", submemberShare);
        return "/templates/enterprise/enterpriseMember/addSubmemberShare";
    }


    /**
     * 保存企业会员共享余额
     *
     * @return
     */
    @RequestMapping(value = "/saveEnterpriseShare", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveEnterpriseShare(EnterpriseSubmemberShare enterpriseSubmemberShare) {
        try {
            if (!BeanUtil.isValid(enterpriseSubmemberShare.getBeginTime(), enterpriseSubmemberShare.getEndTime(),
                    enterpriseSubmemberShare.getFixedPower(), enterpriseSubmemberShare.getFixedAccount())) {
                return TResponse.FAIL("请输入正确参数");
            }

            TResponse tResponse = enterpriseMemberService.saveEnterpriseShare(enterpriseSubmemberShare);
            return tResponse;
        } catch (Exception e) {
            logger.error("保存企业会员共享余额失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存企业子会员共享余额
     *
     * @return
     */
    @RequestMapping(value = "/saveSubmemberShare", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveSubmemberShare(EnterpriseSubmemberShare enterpriseSubmemberShare) {
        try {
            if (!BeanUtil.isValid(enterpriseSubmemberShare.getBeginTime(), enterpriseSubmemberShare.getEndTime(),
                    enterpriseSubmemberShare.getFixedPower(), enterpriseSubmemberShare.getFixedAccount())) {
                return TResponse.FAIL("请输入正确参数");
            }

            //    EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberService.selectByPrimaryKey(enterpriseSubmemberShare.getMemberId());
            //    EnterpriseMemberExample example = new EnterpriseMemberExample();
            //    example.createCriteria().andEnterpriseIdEqualTo(enterpriseSubmember.getBelongEnterpriseId());
            //    List<EnterpriseMember> enterpriseMembers = enterpriseMemberService.selectByExample(example);
            //    if (CollectionUtils.isEmpty(enterpriseMembers)) {
            //        return TResponse.FAIL("没有对应的主会员");
            //    }
            //    EnterpriseSubmemberShare submemberShare = enterpriseSubmemberShareService.selectByMemberId(enterpriseMembers.get(0).getMemberId());
            //    if ("1".equals(enterpriseSubmemberShare.getStatus())) {
            //        if ("0".equals(submemberShare.getStatus())) {
            //            return TResponse.FAIL("对应的主会员,没有开启共享余额");
            //        }
            //    }
            TResponse tResponse = enterpriseMemberService.saveSubmemberShare(enterpriseSubmemberShare);
            return tResponse;
        } catch (Exception e) {
            logger.error("保存企业子会员共享余额失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 跳转企业折扣设置页面
     *
     * @return
     */
    @RequestMapping(value = "/enterpriseDiscount/{enterpriseId}", method = RequestMethod.GET)
    public String enterpriseDiscount(@PathVariable("enterpriseId") Long enterpriseId, Model model) {
        model.addAttribute("enterpriseId", enterpriseId);
        return "/templates/enterprise/enterpriseMember/enterPriseDiscount";
    }

    /**
     * 返回企业折扣列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageEnterpriseDiscount", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageEnterpriseDiscount(BaseSearch baseSearch, Long enterpriseId) {
        PageInfo<EnterpriseDiscountResultVo> pageInfo = tenantDiscountPolicyService.listPageEnterpriseDiscount(baseSearch, enterpriseId);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转增加企业折扣页面
     *
     * @return
     */
    @RequestMapping(value = "/addEnterpriseDiscount/{enterpriseId}", method = RequestMethod.GET)
    public String addEnterpriseDiscount(@PathVariable("enterpriseId") Long enterpriseId, Model model) {
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseId);
        model.addAttribute("enterpriseMember", enterpriseMember);
        return "/templates/enterprise/enterpriseMember/addEnterpriseDiscount";
    }


    /**
     * 跳转编辑企业折扣页面
     *
     * @return
     */
    @RequestMapping(value = "/editEnterpriseDiscount/{discountStationId}", method = RequestMethod.GET)
    public String editEnterpriseDiscount(@PathVariable("discountStationId") Long discountStationId, Model model) {
        TenantDiscountStation tenantDiscountStation = tenantDiscountStationService.selectByPrimaryKey(discountStationId);
        TenantDiscountPolicy tenantDiscountPolicy = tenantDiscountPolicyService.selectAllById(tenantDiscountStation.getDiscountPolicyId());
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectMemberByMemberId(tenantDiscountPolicy.getEnterpriseMemberId());
        model.addAttribute("enterpriseMember", enterpriseMember);
        model.addAttribute("tenantDiscountPolicy", tenantDiscountPolicy);
        model.addAttribute("discountStationId", tenantDiscountStation.getDiscountStationId());
        return "/templates/enterprise/enterpriseMember/editEnterpriseDiscount";
    }


    /**
     * 保存企业会员折扣方案
     *
     * @return
     */
    @RequestMapping(value = "/saveEnterprisePolicy", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveEnterprisePolicy(Long discountPolicyId, String enterpriseName, String discountType, String beginTime,
                                          String endTime, String remark, Long enterpriseMemberId) {
        try {
            if (!BeanUtil.isValid(enterpriseName, discountType, beginTime, endTime, remark)) {
                return TResponse.FAIL("请输入正确参数");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            //优惠类型, 0服务费打折 1 特定服务费（活动价）
            TenantDiscountPolicy tenantDiscountPolicy = new TenantDiscountPolicy();
            //优惠政策名称为 企业名   优惠政策说明 备注
            tenantDiscountPolicy.setPolicyName(enterpriseName);
            tenantDiscountPolicy.setPolicyDesc(remark);
            tenantDiscountPolicy.setDiscountType(discountType);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date begin = sdf.parse(beginTime);
            Date end = sdf.parse(endTime);
            tenantDiscountPolicy.setBeginTime(begin);

            tenantDiscountPolicy.setEnterpriseMemberId(enterpriseMemberId);
            tenantDiscountPolicy.setEndTime(end);
            tenantDiscountPolicy.setStatus("0");
            tenantDiscountPolicy.setTenantCode(user.getTenantCode());
            //优惠用户类型 0 全部 1普通用户 2企业用户
            tenantDiscountPolicy.setPolicyMemberType("2");

            if (discountPolicyId == null) {
                tenantDiscountPolicyService.insertReturnKey(tenantDiscountPolicy);
            } else {
                tenantDiscountPolicy.setDiscountPolicyId(discountPolicyId);
                tenantDiscountPolicyService.updateByPrimaryKeySelective(tenantDiscountPolicy);
            }


            return TResponse.SUCCESS_DATA(tenantDiscountPolicy);
        } catch (Exception e) {
            logger.error("保存企业会员折扣方案失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存企业会员方案时段
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateEnterpriseDiscountTime", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateDiscountTime(@RequestBody String tenantDiscountTime) {
        TenantUser user = ShiroUtils.getSessionUser();

        try {
            String timeType = JSONObject.parseObject(tenantDiscountTime).getString("timeType");
            String discountType = JSONObject.parseObject(tenantDiscountTime).getString("discountType");
            Long discountPolicyId = JSONObject.parseObject(tenantDiscountTime).getLong("discountPolicyId");

            if (!BeanUtil.isValid(timeType, discountType, discountPolicyId)) {
                return TResponse.FAIL("请输入正确的参数");
            }

            //全天
            if ("1".equals(timeType)) {
                BigDecimal elecPrice = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("elecPrice");
                BigDecimal servicePrice = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("servicePrice");
                BigDecimal discount = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("discount");

                tenantDiscountTimeService.insertDiscountTime(discountPolicyId, null, discountType, timeType, elecPrice, servicePrice, discount, null, user.getTenantCode());
            } else {
                List<DiscountTimeSaveVo> discountTimeSaveVoList = JSONObject.parseArray(JSONObject.parseObject(tenantDiscountTime).getString("discountTimeSaveVoList"), DiscountTimeSaveVo.class);

                List<String> list = new ArrayList<String>();
                for (DiscountTimeSaveVo discountTimeSaveVo : discountTimeSaveVoList) {
                    list.add(discountTimeSaveVo.getStartPeriod() + "-" + discountTimeSaveVo.getEndPeriod());
                }

                Boolean overlappTime = TimeUtil.isOverlappTime(list);

                if (overlappTime == true) {
                    return TResponse.FAIL("时间重叠");
                }

                tenantDiscountTimeService.insertDiscountTime(discountPolicyId, null, discountType, timeType, null, null, null, discountTimeSaveVoList, user.getTenantCode());
            }

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存企业会员方案时段失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存企业会员折扣桩群
     *
     * @return
     */
    @RequestMapping(value = "/saveEnterpriseStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveEnterpriseStation(@RequestBody String enterpriseStationList) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();
            List<DiscountStationSaveVo> discountStationSaveVOS = JSON.parseArray(enterpriseStationList, DiscountStationSaveVo.class);
            TResponse tResponse = tenantDiscountStationService.saveEnterpriseStation(user.getTenantCode(), discountStationSaveVOS);
            return tResponse;
        } catch (Exception e) {
            logger.error("保存企业会员折扣桩群失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 返回企业会员所有桩群(已选/未选)
     *
     * @return
     */
    @RequestMapping(value = "/listStationByEnterprisePolicy", method = RequestMethod.POST)
    @ResponseBody
    public TResponse listStationByEnterprisePolicy(Long enterpriseId) {
        TenantUser user = ShiroUtils.getSessionUser();
        try {
            //返回结果列表
            ArrayList<EnterprieseStationVo> enterpriseDiscountResultVos = new ArrayList<>();

            List<ElecStation> elecStations = elecStationService.listAllStationByTenantCode(user.getTenantCode());

            EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseId);

            //查询是否存在方案
            TenantDiscountPolicyExample example = new TenantDiscountPolicyExample();
            example.createCriteria().andEnterpriseMemberIdEqualTo(enterpriseMember.getMemberId());
            //可能是多个方案
            List<TenantDiscountPolicy> tenantDiscountPolicyList = tenantDiscountPolicyService.selectByExample(example);

            ArrayList<Long> existStationDiscountList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(tenantDiscountPolicyList)) {
                for (TenantDiscountPolicy tenantDiscountPolicy : tenantDiscountPolicyList) {
                    TenantDiscountStationExample tenantDiscountStationExample = new TenantDiscountStationExample();
                    tenantDiscountStationExample.createCriteria().andDiscountPolicyIdEqualTo(tenantDiscountPolicy.getDiscountPolicyId());
                    List<TenantDiscountStation> tenantDiscountStations = tenantDiscountStationService.selectByExample(tenantDiscountStationExample);
                    if (!CollectionUtils.isEmpty(tenantDiscountStations)) {
                        for (TenantDiscountStation tenantDiscountStation : tenantDiscountStations) {
                            existStationDiscountList.add(tenantDiscountStation.getElecStationId());
                        }
                    }
                }


                for (ElecStation elecStation : elecStations) {
                    EnterprieseStationVo enterprieseStationVo = new EnterprieseStationVo();
                    enterprieseStationVo.setBizType(elecStation.getBizType());
                    enterprieseStationVo.setStationName(elecStation.getStationName());
                    enterprieseStationVo.setElecStationId(elecStation.getElecStationId());
                    enterprieseStationVo.setStatus("0");
                    for (Long aLong : existStationDiscountList) {
                        if (aLong.equals(elecStation.getElecStationId())) {
                            enterprieseStationVo.setStatus("1");
                        }
                    }
                    enterpriseDiscountResultVos.add(enterprieseStationVo);
                }
                return TResponse.SUCCESS_DATA(enterpriseDiscountResultVos);
            } else {
                for (ElecStation elecStation : elecStations) {

                    EnterprieseStationVo enterprieseStationVo = new EnterprieseStationVo();
                    enterprieseStationVo.setStatus("0");
                    enterprieseStationVo.setBizType(elecStation.getBizType());
                    enterprieseStationVo.setStationName(elecStation.getStationName());
                    enterprieseStationVo.setElecStationId(elecStation.getElecStationId());
                    enterpriseDiscountResultVos.add(enterprieseStationVo);
                }
                return TResponse.SUCCESS_DATA(enterpriseDiscountResultVos);
            }
        } catch (Exception e) {
            logger.error("查询企业会员对应桩群失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 删除企业折扣桩群
     *
     * @param discountStationId
     * @return
     */
    @RequestMapping(value = "/deleteEnterpriseDiscountStation", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse deleteEnterpriseDiscountStation(Long discountStationId) {
        try {
            TResponse tResponse = tenantDiscountPolicyService.deleteEnterpriseDiscountStation(discountStationId);
            return tResponse;
        } catch (Exception e) {
            logger.error("删除企业折扣桩群失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 批量删除企业折扣桩群
     *
     * @param discountStationList
     * @return
     */
    @RequestMapping(value = "/deleteBatchEnterpriseDiscountStation", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse deleteBatchEnterpriseDiscountStation(@RequestParam List<Long> discountStationList) {
        try {
            TenantDiscountStationExample example = new TenantDiscountStationExample();
            example.createCriteria().andDiscountStationIdIn(discountStationList);
            tenantDiscountStationService.deleteByExample(example);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("批量删除企业折扣桩群失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 编辑企业会员方案时段(新增方案)
     *
     * @return
     */
    @RequestMapping(value = "/saveEditDiscountTime", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveEditDiscountTime(@RequestBody String tenantDiscountTime) {
        TenantUser user = ShiroUtils.getSessionUser();

        try {
            String timeType = JSONObject.parseObject(tenantDiscountTime).getString("timeType");
            String discountType = JSONObject.parseObject(tenantDiscountTime).getString("discountType");
            Long discountPolicyId = JSONObject.parseObject(tenantDiscountTime).getLong("discountPolicyId");
            Long discountStationId = JSONObject.parseObject(tenantDiscountTime).getLong("discountStationId");


            if (!BeanUtil.isValid(timeType, discountType, discountPolicyId)) {
                return TResponse.FAIL("请输入正确的参数");
            }

            //全天
            if ("1".equals(timeType)) {
                BigDecimal elecPrice = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("elecPrice");
                BigDecimal servicePrice = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("servicePrice");
                BigDecimal discount = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("discount");

                tenantDiscountTimeService.insertDiscountTime(discountPolicyId, null, discountType, timeType, elecPrice, servicePrice, discount, null, user.getTenantCode(), discountStationId);
            } else {
                List<DiscountTimeSaveVo> discountTimeSaveVoList = JSONObject.parseArray(JSONObject.parseObject(tenantDiscountTime).getString("discountTimeSaveVoList"), DiscountTimeSaveVo.class);

                List<String> list = new ArrayList<String>();
                for (DiscountTimeSaveVo discountTimeSaveVo : discountTimeSaveVoList) {
                    list.add(discountTimeSaveVo.getStartPeriod() + "-" + discountTimeSaveVo.getEndPeriod());
                }

                Boolean overlappTime = TimeUtil.isOverlappTime(list);

                if (overlappTime == true) {
                    return TResponse.FAIL("时间重叠");
                }

                tenantDiscountTimeService.insertDiscountTime(discountPolicyId, null, discountType, timeType, null, null, null, discountTimeSaveVoList, user.getTenantCode(), discountStationId);
            }

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存企业会员方案时段失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转分配余额页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/editAmount/{memberId}", method = RequestMethod.GET)
    public String editEnterpriseAmount(@PathVariable("memberId") Long memberId, Model model) {
        EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberService.selectByPrimaryKey(memberId);
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseSubmember.getBelongEnterpriseId());
        MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(enterpriseMember.getMemberId());
        model.addAttribute("enterpriseAccount", memberAccount.getEnterpriseAccount());
        model.addAttribute("memberId", memberId);
        return "/templates/enterprise/enterpriseMember/editEnterpriseAmount";
    }


    /**
     * 获取手机短信验证码
     */
    @RequestMapping(value = "/getEnterpriseAmountAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public TResponse getEnterpriseAmountAuthCode(HttpSession session) {
        TenantUser user = ShiroUtils.getSessionUser();
        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
        //验证码
        String smscode = uidGenerator.genSmsAuthCode();

        SendSmsResponse sendResult = AliyunSmsUtil.sendSms(user.getMobile(), smscode, AliyunSmsTemplateEnum.EDIT_ENTERPRISE_AMOUNT, tenant.getSmsSign());

        if (sendResult == null) {
            logger.error("短信系统异常");
            return TResponse.FAIL("短信系统异常");
        }

        if ("OK".equals(sendResult.getCode())) {
            // 更新sms表
            tenantSmsService.updateTenantSmsByTenantCode(user.getTenantCode(), user.getMobile(), "0", "tenant,getEnterpriseAmountAuthCode:获取验证码 ,进行企业会员分配余额功能:" + user.getMobile(), "获取验证码 ,进行企业会员分配余额功能");
        } else {
            logger.error("短信系统异常:" + sendResult.getMessage());
        }


        //将登录验证码保存到会话中
        String sessionAttr = ShiroConstants.SESSION_EDIT_ENTERPRISE_AMOUNT_KEY + user.getMobile();
        String sessionAuthCode = smscode + System.currentTimeMillis();
        session.setAttribute(sessionAttr, sessionAuthCode);

        logger.error("获取手机短信验证码 mobile:{},sessionAttr:{},sessionAuthCode:{}", user.getMobile(), sessionAttr, sessionAuthCode);

        return TResponse.SUCCESS("验证码已发送");
    }


    /**
     * 保存企业分配余额
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/saveEnterpriseAmount", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse saveEnterpriseAmount(Long memberId, BigDecimal enterpriseAccount, HttpSession session, String verificationCode) {
        try {
            TenantUser sessionUser = ShiroUtils.getSessionUser();

//            String sessionAttr = ShiroConstants.SESSION_EDIT_ENTERPRISE_AMOUNT_KEY + sessionUser.getMobile();
//            String sessionAuthCode = (String) session.getAttribute(sessionAttr);
//            if (StringUtils.isBlank(sessionAuthCode)) {
//                return TResponse.FAIL("未申请验证码");
//            }
//
//            if (!verificationCode.equals(sessionAuthCode.substring(0, 6))) {
//                return TResponse.FAIL("验证码错误");
//            }
            if (enterpriseAccount.compareTo(new BigDecimal(0)) < 0) {
                return TResponse.FAIL("请输入大于0的金额");
            }
            EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberService.selectByPrimaryKey(memberId);
            if (enterpriseSubmember == null) {
                return TResponse.FAIL("不存在此子会员");
            }
            EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseSubmember.getBelongEnterpriseId());
            if (enterpriseMember == null) {
                return TResponse.FAIL("不存在对应的主会员");
            }
            TResponse tResponse = memberAccountService.saveEnterpriseAmount(enterpriseMember.getMemberId(), enterpriseSubmember.getMemberId(),
                    enterpriseAccount);
            return tResponse;
        } catch (Exception e) {
            logger.error("保存企业分配余额", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转子会员余额记录页面
     *
     * @return
     */
    @RequestMapping(value = "/subMemberAmountRecord/{memberId}", method = RequestMethod.GET)
    public String subMemberAmountRecord(@PathVariable("memberId") Long memberId, Model model) {
        model.addAttribute("memberId", memberId);
        return "/templates/enterprise/enterpriseMember/subMemberAmountRecord";
    }

    /**
     * 返回子会员余额记录列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageSubMemberAmountRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageSubMemberAmountRecord(MemberAccountRecordSearch memberAccountRecordSearch) {
        PageInfo<MemberAccountRecordResultVo> pageInfo = memberAccountRecordService.listPageSubMemberAmountRecord(memberAccountRecordSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出子会员余额记录
     *
     * @param memberAccountRecordSearch
     * @return
     */
    @RequestMapping(value = "/exportSubMemberAmountRecord", method = RequestMethod.GET)
    @ResponseBody
    public TResponse exportSubMemberAmountRecord(MemberAccountRecordSearch memberAccountRecordSearch, HttpServletResponse response) {
        ExportUtils.setDefaultPaging(memberAccountRecordSearch);
        if (memberAccountRecordSearch.getCount() == 0 || memberAccountRecordSearch.getCount() == null) {
            memberAccountRecordSearch.setCount(memberAccountRecordSearch.getLimit());
        }

        if (memberAccountRecordSearch.getCount() > 150000) {
            return TResponse.FAIL("最多导出十五万数据");
        }

        if (memberAccountRecordSearch.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        memberAccountRecordSearch.setOffset(memberAccountRecordSearch.getLimit() * (memberAccountRecordSearch.getOffset() - 1));

        List<MemberAccountRecordPrintVo> memberAccountRecordPrintVos = memberAccountRecordService.listSubMemberAmountRecord(memberAccountRecordSearch);

        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {

            logger.info(memberAccountRecordSearch.getTenantCode() + ",enterpriseMember/exportSubMemberAmountRecord,startTime:{},endTime:{},count:{}",
                    memberAccountRecordSearch.getStartTime(), memberAccountRecordSearch.getEndTime(), memberAccountRecordSearch.getCount());

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), MemberAccountRecordPrintVo.class).sheet("子会员余额记录").doWrite(memberAccountRecordPrintVos);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出子会员余额记录失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 回收子会员
     *
     * @return
     */
    @RequestMapping(value = "/recoveredAmount", method = RequestMethod.POST)
    @ResponseBody
    public TResponse recoveredAmount(Long memberId) {
        try {
            TResponse tResponse = enterpriseSubmemberService.updateRecoveredAmount(memberId);
            return tResponse;
        } catch (Exception e) {
            logger.error("回收子会员失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 导出企业主会员列表
     */
    @ResponseBody
    @RequestMapping("/exportEnterpriseMember")
    public TResponse exportEnterpriseMember(EnterpriseMemberSearch enterpriseMemberSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        ExportUtils.setDefaultPaging(enterpriseMemberSearch);
        if (enterpriseMemberSearch.getCount() == 0 || enterpriseMemberSearch.getCount() == null) {
            enterpriseMemberSearch.setCount(enterpriseMemberSearch.getLimit());
        }
        if (enterpriseMemberSearch.getCount() > 10000) {
            enterpriseMemberSearch.setCount(10000);
        }

        //导出拼接开始条数
        enterpriseMemberSearch.setOffset(enterpriseMemberSearch.getLimit() * (enterpriseMemberSearch.getOffset() - 1));

        try {
            List<EnterpriseMemberPrintVo> list = enterpriseMemberService.exportEnterpriseMember(enterpriseMemberSearch);

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("企业会员列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), EnterpriseMemberPrintVo.class).sheet("企业会员列表").doWrite(list);

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出企业会员列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }

    }


    /**
     * 重置企业主会员
     *
     * @return
     */
    @RequestMapping(value = "/updateEnterprisePassword", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateEnterprisePassword(Long memberId, String password, String verifyPassword) {
        try {
            if (!BeanUtil.isValid(password, verifyPassword)) {
                return TResponse.FAIL("请输入正确的参数");
            }

            if (!password.equals(verifyPassword)) {
                return TResponse.FAIL("两次密码不一致");
            }

            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);

            if (!"1".equals(memberInfo.getMemberType())) {
                return TResponse.FAIL("此用户不是企业主会员");
            }

            if (memberInfo.getBelongEnterpriseId() == null) {
                return TResponse.FAIL("此用户enterpriseId为空");
            }


            TenantUserExample example = new TenantUserExample();
            example.createCriteria().andEnterpriseIdEqualTo(memberInfo.getBelongEnterpriseId());
            List<TenantUser> tenantUsers = tenantUserService.selectByExample(example);
            if (!CollectionUtils.isEmpty(tenantUsers)) {
                TenantUser tenantUser = tenantUsers.get(0);

                TResponse tResponse = enterpriseMemberService.resetPassword(tenantUser, password);

                return tResponse;
            }
            return TResponse.FAIL("不存在此企业主会员,可能更改过手机号码");

        } catch (Exception e) {
            logger.error("重置企业主会员失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 冻结/解冻企业主会员
     * @param memberId
     * @return
     */
    @RequestMapping(value = "/updateEnterpriseMemberStatus",method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateEnterpriseMemberStatus(Long memberId){
        try {
            TResponse tResponse=enterpriseMemberService.updateStatus(memberId);
            return tResponse;
        } catch (Exception e) {
            return TResponse.FAIL("主会员更新状态失败");
        }
    }

    /**
     * 修改企业状态
     * @return
     */
    @RequestMapping(value = "/updateEnterpriseStatus",method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateEnterpriseStatus(Long id, String status){
        try {
            EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(id);
            enterpriseMember.setStatus(status);
            enterpriseMemberService.updateByPrimaryKeySelective(enterpriseMember);

            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("主会员更新状态失败");
        }
    }

    @RequestMapping(value = "/edit/{id}")
    public String editEnterprise(Model model, @PathVariable("id") Long id) {
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(id);
        model.addAttribute("enterprise", enterpriseMember);
        return "/templates/enterprise/enterpriseMember/editEnterprise";
    }

    @RequestMapping(value = "/detail/{id}")
    public String detailEnterprise(Model model, @PathVariable("id") Long id) {
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(id);
        model.addAttribute("enterprise", enterpriseMember);
        return "/templates/enterprise/enterpriseMember/detailEnterprise";
    }

    @ResponseBody
    @RequestMapping(value = "/updateEnterprise",method = RequestMethod.POST)
    public TResponse updateEnterprise(EnterpriseMember enterpriseMember,
                                      @RequestParam(value = "file1", required = false) MultipartFile file1,
                                      @RequestParam(value = "file2", required = false) MultipartFile file2)  {
        TenantUser user = ShiroUtils.getSessionUser();
        if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
            enterpriseMember.setCompanyImg1(imgUrl);
        }
        if (file2 != null && file2.getSize() != 0 && file2.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file2);
            enterpriseMember.setCompanyImg1(imgUrl);
        }

        EnterpriseMemberApply apply = enterpriseMemberApplyService.selectByEnterpriseId(enterpriseMember.getEnterpriseId());
        if (apply != null) {
            apply.setEnterpriseName(enterpriseMember.getEnterpriseName());
            apply.setEnterpriseCredit(enterpriseMember.getLicense());
            apply.setTaxPayerCode(enterpriseMember.getTaxPayerCode());
            apply.setCompanyImg1(enterpriseMember.getCompanyImg1());
            apply.setEnterpriseBank(enterpriseMember.getEnterpriseBank());
            apply.setEnterpriseBankAccount(enterpriseMember.getEnterpriseBankAccount());
            apply.setEnterpriseOwner(enterpriseMember.getEnterpriseOwner());
            apply.setOwnerMobile(enterpriseMember.getOwnerMobile());
            apply.setPhone(enterpriseMember.getPhone());
            apply.setAddress(enterpriseMember.getAddress());
            enterpriseMemberApplyService.updateByPrimaryKeySelective(apply);

        }


        enterpriseMemberService.updateByPrimaryKeySelective(enterpriseMember);
        return TResponse.SUCCESS();
    }

    /**
     * 企业充值
     */
    @ResponseBody
    @RequestMapping(value = "/updateEnterpriseForRecharge",method = RequestMethod.POST)
    public TResponse updateEnterpriseForRecharge(Long id, BigDecimal money) {
        enterpriseMemberService.updateEnterpriseForRecharge(id, money);
        return TResponse.SUCCESS();

    }


    /**
     * 企业充值
     */
    @ResponseBody
    @RequestMapping(value = "/updateEnterpriseForCredit",method = RequestMethod.POST)
    public TResponse updateEnterpriseForCredit(Long id, BigDecimal creditAmount) {
        enterpriseMemberService.updateEnterpriseForCredit(id, creditAmount);
        return TResponse.SUCCESS();

    }





}
